package com.atguigu.gmall.payment.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.service.PaymentService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/7/29 9:23
 * @Version 1.0
 */
@Component
public class PaymentReceiver {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderFeignClient orderFeignClient;


    /**
     * 监听关闭交易记录信息
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_CLOSE,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_CLOSE),
            key = {MqConst.ROUTING_PAYMENT_CLOSE}
    ))
    public void paymentClose(Long orderId, Message message, Channel channel){
        try {
            //  判断
            if (null != orderId){
                //  根据订单Id 获取orderInfo
                OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
                //  判断orderInfo
                if (null != orderInfo){
                    //  利用业务字段防止消息重复消费.
                    PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderInfo.getOutTradeNo(), PaymentType.ALIPAY.name());
                    //  判断
                    if (null!=paymentInfo && !"CLOSED".equals(paymentInfo.getPaymentStatus())){
                        //  关闭交易记录.
                        this.paymentService.closePaymentInfo(orderId);
                        //  this.paymentService.closePaymentInfo(paymentInfo.getId());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
